<template>
  <div class="app-container">
    <el-row :gutter="20" v-if="!obj.budgetOneId">
      <el-col :sm="24" :lg="29" style="padding-left: 20px">
        <el-card class="update-log update-log-1">
          <div class="form-list-content">
            <div class="report-form-list-content report-form-list-content-1">
              <el-form-item prop="budgetOneId" label="一上预算编制">
                <el-input v-model="obj.budgetOneId"
                          placeholder="请选择一上编制"
                          @focus="openProjectModel"
                          prefix-icon="Search"
                          readonly
                          style="width: 300px;" />
              </el-form-item>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider/>
    <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" label-width="auto" label-suffix="：" :disabled="oper === 'view'">
      <div v-if="obj.budgetOneId">
        <div class="form-label form-label-1 totalFund" style="width: auto;">
          项目预算
          一上申报金额：<span>¥ {{ obj.applyOneFund ? obj.applyOneFund : 0 }}</span>，
          一下批复金额：<span>¥ {{ obj.approveOneFund ? obj.approveOneFund : 0 }}</span>
        </div>
        <!-- 项目基本信息 -->
        <el-row :gutter="24">
          <el-col :sm="24" :lg="29" style="padding-left: 1.25rem">
            <h2>项目基本信息</h2>
            <el-card class="update-log" shadow="hover">
              <div class="form-list-content">
                <el-form-item label="项目编码" prop="code">
                  <el-input v-model="obj.code" placeholder="自动生成" disabled/>
                </el-form-item>
                <el-form-item label="项目名称" prop="name">
                  <el-input v-model="obj.name" placeholder="请输入项目名称" />
                </el-form-item>
                <el-form-item label="存续状态" prop="viability">
                  <el-radio-group v-model="obj.viability" @change="viabilityChange">
                    <el-radio-button v-for="(item,index) in getDictList('BudgetProjectViability')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="项目起始年度" prop="startTime">
                  <el-date-picker v-model="obj.startTime" type="year" placeholder="请选择项目起始年度" value-format="YYYY" :disabled-date="disabledDateStart" @change="startTimeChange" />
                </el-form-item>
                <el-form-item label="项目终止年度" prop="endTime">
                  <el-date-picker v-model="obj.endTime" type="year" placeholder="请选择项目终止年度" value-format="YYYY" :disabled-date="disabledDateEnd" :disabled="isDisabledEndTime" @change="endTimeChange" />
                </el-form-item>
                <el-form-item label="项目来源" prop="source">
                  <el-radio-group v-model="obj.source">
                    <el-radio-button v-for="(item,index) in getDictList('BudgetProjectSource')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="项目属性" prop="attribute">
                  <el-radio-group v-model="obj.attribute">
                    <el-radio-button v-for="(item,index) in getDictList('BudgetProjectAttribute')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="申请财政金额" prop="totalFund">
                  <el-input-number v-model="obj.totalFund" placeholder="请输入申请财政金额" :min="0" :precision="2" disabled/>
                </el-form-item>
                <el-form-item label="社会投入资金" prop="putinFund">
                  <el-input-number v-model="obj.putinFund" placeholder="请输入社会投入资金" :min="0" :precision="2" />
                </el-form-item>
                <el-form-item label="当年资金" prop="currFund">
                  <el-input-number v-model="obj.currFund" placeholder="请输入当年资金" :min="0" :precision="2" />
                </el-form-item>
                <el-form-item label="资金性质" prop="fundType">
                  <el-select v-model="obj.fundType" placeholder="请选择" clearable filterable>
                    <el-option v-for="item in getDictList('BudgetFundType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
                  </el-select>
                </el-form-item>
                <el-form-item label="用款单位" prop="useGovId">
                  <el-cascader v-model="obj.useGovId" :options="arrChangeTreeFn(governmentList)" :props="{label: 'governmentName', value: 'id', checkStrictly: true}" clearable/>
                </el-form-item>
                <el-form-item label="申报单位" prop="applyGovId">
                  <el-cascader v-model="obj.applyGovId" :options="arrChangeTreeFn(governmentList)" :props="{label: 'governmentName', value: 'id', checkStrictly: true}" clearable/>
                </el-form-item>
                <el-form-item label="上一年项目预算安排情况" prop="previousArrange">
                  <el-input-number v-model="obj.previousArrange" placeholder="请输入上一年项目预算安排情况" :min="0" :precision="2" />
                </el-form-item>
              </div>
              <div class="form-list-content">
                <el-form-item label="主管部门" prop="managerOrgId">
                  <selectBudgetCompetent v-model="obj.managerOrgId" keyName="id" keyShow="name" placeholder="主管部门" title="预算主管部门查询" @onchange="changeManagerOrgId" />
                </el-form-item>
                <el-form-item label="主管部门联系人" prop="managerName">
                  <el-input v-model="obj.managerName" placeholder="请输入主管部门联系人" />
                </el-form-item>
                <el-form-item label="主管部门联系电话" prop="managerUserContact">
                  <el-input v-model="obj.managerUserContact" placeholder="请输入主管部门联系电话" />
                </el-form-item>
              </div>
              <div class="form-list-content">
                <el-form-item label="项目实施单位" prop="workGovId">
                  <el-cascader v-model="obj.workGovId" :options="arrChangeTreeFn(governmentList)" :props="{label: 'governmentName', value: 'id', checkStrictly: true}" clearable/>
                </el-form-item>
                <el-form-item label="项目负责人" prop="workUserId">
                  <User v-model="obj.workUserId" keyName="id" keyShow="name" placeholder="负责人" title="用户查询" />
                </el-form-item>
                <el-form-item label="项目负责联系电话" prop="workUserContact">
                  <el-input v-model="obj.workUserContact" placeholder="请输入项目负责联系电话" />
                </el-form-item>
              </div>
              <div class="form-list-content-1">
                <el-form-item label="项目概述" prop="summarize">
                  <el-input v-model="obj.summarize" :rows="5" type="textarea" class="textarea-1" placeholder="请输入项目概述" />
                </el-form-item>
              </div>
              <div class="form-list-content-1">
                <el-form-item label="设立依据及申报理由" prop="reason">
                  <el-input v-model="obj.reason" :rows="5" type="textarea" class="textarea-1" placeholder="请输入设立依据及申报理由" />
                </el-form-item>
              </div>
              <div class="form-list-content">
                <el-form-item label="是否债券可用项目" prop="isDebenture">
                  <el-radio-group v-model="obj.isDebenture">
                    <el-radio-button v-for="(item,index) in getDictList('BudgetProjectDebenture')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否科研项目" prop="isScientific">
                  <el-radio-group v-model="obj.isScientific">
                    <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否基建项目" prop="isConstruction">
                  <el-radio-group v-model="obj.isConstruction">
                    <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-card>
            <el-card class="update-log" shadow="hover" v-if="obj.isConstruction === '1'">
              <label class="form-label form-label-2">基建类项目信息:</label>
              <div class="form-list-content">
                <el-form-item label="基建立项情况" prop="constructionDesc">
                  <el-select v-model="obj.constructionDesc" class="m-2" placeholder="请选择" clearable filterable>
                    <el-option v-for="item in getDictList('BudgetProjectConstruction')" :key="item.value" :label="`${item.key} - ${item.value}`" :value="item.key" />
                  </el-select>
                </el-form-item>
                <el-form-item label="是否代建项目" prop="isAgent">
                  <el-radio-group v-model="obj.isAgent" @change="obj.agentGovId = null">
                    <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="代建单位" prop="agentGovId" v-if="obj.isAgent === '1'">
                  <el-cascader v-model="obj.agentGovId" :options="arrChangeTreeFn(governmentList)" :props="{label: 'governmentName', value: 'id', checkStrictly: true}" clearable />
                </el-form-item>
              </div>
            </el-card>
            <br />
          </el-col>
        </el-row>
        <el-divider />
        <!-- 项目预算 -->
        <el-row :gutter="24">
          <el-col :sm="24" :lg="24" style="padding-left: 1.25rem">
            <div class="budget-title budget-title-1">
              <div class="budget-title-left">
                <h2>项目预算</h2>
                <el-form-item class="form-radio1" prop="isGovernmentPurchase" label="是否政府采购">
                  <el-switch v-model="obj.isGovernmentPurchase"
                             active-value="1"
                             active-text="是"
                             inactive-value="0"
                             inactive-text="否" />
                </el-form-item>
                <el-button class="ico-list" icon="Plus" type="primary" @click="addGovernmentBudget" v-if="obj.isGovernmentPurchase === '1'">新增政府采购</el-button>
              </div>
            </div>
            <div v-show="obj.isGovernmentPurchase === '1'">
              <template v-for="(item,index) in purchases" :key="index">
                <div class="budget-title">
                  <label class="form-label">政府采购{{ index + 1 }}</label>
                </div>
                <el-card class="update-log" shadow="hover">
                  <div class="form-list-content">
                    <el-form-item label="采购项目" prop="purchaseItem">
                      <el-input v-model="item.purchaseItem" placeholder="请输入采购项目" />
                    </el-form-item>
                    <el-form-item label="采购品目" prop="purchaseKind">
                      <el-input v-model="item.purchaseKind" placeholder="请输入采购品目" />
                    </el-form-item>
                    <el-form-item label="采购需求概况" prop="purchaseRequire">
                      <el-input v-model="item.purchaseRequire" placeholder="请输入采购需求概况" />
                    </el-form-item>
                    <el-form-item label="预计采购时间" prop="purchaseDate">
                      <el-date-picker v-model="item.purchaseDate" placeholder="请输入预计采购时间" type="date" style="width: 166px;" value-format="YYYY-MM-DD" />
                    </el-form-item>
                  </div>
                  <div class="form-list-content">
                    <el-form-item label="资金性质" prop="purchaseAttr">
                      <el-input v-model="item.purchaseAttr" placeholder="请输入资金性质" />
                    </el-form-item>
                    <el-form-item label="采购金额" prop="purchaseFund">
                      <el-input-number v-model="item.purchaseFund" placeholder="请输入采购金额" :min="0" :precision="2" />
                    </el-form-item>
                    <el-form-item label="单价" prop="purchasePrice">
                      <el-input-number v-model="item.purchasePrice" placeholder="请输入单价" :min="0" :precision="2" />
                    </el-form-item>
                    <el-form-item label="采购数量" prop="purchaseNum">
                      <el-input-number v-model="item.purchaseNum" placeholder="请输入采购数量" :min="0" :precision="2" />
                    </el-form-item>
                    <el-form-item label="计量单位" prop="purchaseUnit">
                      <el-select v-model="item.purchaseUnit" class="m-2" placeholder="请选择" clearable filterable>
                        <el-option v-for="item1 in getDictList('Unit')" :key="item1.key" :label="`${item1.key} - ${item1.value}`" :value="item1.key" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="专项资金名称" prop="purchaseAttr">
                      <el-input v-model="item.fundName" placeholder="请输入资金性质" />
                    </el-form-item>
                    <el-form-item label="资金来源" prop="purchaseAttr">
                      <el-input v-model="item.fundSource" placeholder="请输入资金性质" />
                    </el-form-item>
                  </div>
                  <div class="" style="width: 100%">
                    <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeGovernmentBudget(index)">删除</el-button>
                  </div>
                </el-card>
              </template>
            </div>
          </el-col>
        </el-row>
        <el-divider />
        <!-- 项目预算明细 -->
        <el-row :gutter="24">
          <el-col :sm="24" :lg="24" style="padding-left: 1.25rem">
            <div class="budget-title">
              <h2>项目预算明细</h2>
              <el-button class="ico-list" icon="Plus" type="primary" @click="addItem">新增</el-button>
            </div>
            <div class="form-list" v-for="(item,index) in items" :key="index">
              <label class="form-label">项目预算明细{{ index + 1 }}:</label>
              <el-card class="update-log update-log-1" shadow="hover">
                <div class="form-list-content">
                  <el-form-item label="年度">
                    <el-date-picker v-model="item.year" type="year" placeholder="请选择年度" style="width: 166px;" value-format="YYYY" @change="buildYearsRefreshTotalFund" :disabled-date="disabledDate1" />
                  </el-form-item>
                  <el-form-item label="明细项目类别">
                    <el-cascader v-model="item.itemType" :props="{label: 'itemTypeName', value: 'id'}" :options="itemTypeList" @change="categoryChange($event,item,index)" />
                  </el-form-item>
                  <el-form-item label="开支范围">
                    <selectBudgetItemRange v-model="item.itemRange" keyName="id" keyShow="itemRangeName" placeholder="开支范围" title="开支范围查询" />
                  </el-form-item>
                  <el-form-item label="开支内容">
                    <el-input v-model="item.itemName" placeholder="请输入开支内容，最多输入100个字符" />
                  </el-form-item>
                  <el-form-item label="功能分类">
                    <el-select v-model="item.itemFunctionType" class="m-2" placeholder="请选择" clearable filterable>
                      <el-option v-for="item1 in getDictList('BudgetItemFunctionType')" :key="item1.key" :label="`${item1.key} - ${item1.value}`" :value="item1.key" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="经济分类">
                    <el-select v-model="item.itemEconomyType" class="m-2" placeholder="请选择" clearable filterable>
                      <el-option v-for="item1 in getDictList('BudgetItemEconomyType')" :key="item1.key" :label="`${item1.key} - ${item1.value}`" :value="item1.key" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="计量单位">
                    <el-input v-model="item.unit" placeholder="请输入计量单位，最多输入100个字符" />
                  </el-form-item>
                  <el-form-item label="单价/支出标准">
                    <el-input-number v-model="item.price" placeholder="请输入单价/支出标准" @change="buildYearsRefreshTotalFund" :min="0" :precision="2" />
                  </el-form-item>
                  <el-form-item label="工作量">
                    <el-input-number v-model="item.num" placeholder="请输入工作量" @change="buildYearsRefreshTotalFund" :min="0" :precision="2" />
                  </el-form-item>
                  <el-form-item label="测算依据及说明">
                    <el-input v-model="item.reason" placeholder="请输入测算依据及说明" />
                  </el-form-item>
                  <el-form-item label="按标准测算金额">
                    <el-input-number :value="item.price * item.num" disabled placeholder="按标准测算金额" :min="0" :precision="2" />
                  </el-form-item>
                </div>
                <div class="form-list-content-1">
                  <el-form-item label="备注">
                    <el-input v-model="item.remark" :rows="4" :cols="100" type="textarea" class="textarea-1" placeholder="请输入备注，最多输入3000个字符" />
                  </el-form-item>
                  <div class="" style="width: 100%">
                    <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(index)">删除</el-button>
                  </div>
                </div>
              </el-card>
            </div>
          </el-col>
        </el-row>
        <el-divider />
        <!-- 分年度资金计划 -->
        <el-row :gutter="24">
          <el-col :sm="24" :lg="24" style="padding-left: 1.25rem">
            <div class="budget-title">
              <h2>分年度资金计划</h2>
            </div>
            <div class="form-list" v-for="(item,index) in years" :key="index">
              <el-card class="update-log update-log-1" shadow="hover">
                <label class="form-label">{{ item.year }}年度:</label>
                <div class="form-list-content">
                  <el-form-item label="单位申报数">
                    <el-input-number v-model="item.applyFund" disabled placeholder="请输入单位申报数" :precision="2" />
                  </el-form-item>
                  <el-form-item label="部门审核数">
                    <el-input-number v-model="item.approveFund" disabled placeholder="请输入部门审核数" :precision="2" />
                  </el-form-item>
                  <el-form-item label="预算审核数">
                    <el-input-number v-model="item.budgetFund" disabled placeholder="请输入预算审核数" :precision="2" />
                  </el-form-item>
                  <el-form-item label="纳入预算金额">
                    <el-input-number v-model="item.bringFund" disabled placeholder="请输入纳入预算金额" :precision="2" />
                  </el-form-item>
                  <el-form-item label="三保目录">
                    <el-select v-model="item.thirdCatalog" class="m-2" placeholder="请选择三保目录" clearable filterable>
                      <el-option v-for="m in thirdCatalogList" :key="m.id" :label="`${m.thirdCode} - ${m.thirdName}`" :value="m.id" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="热点分类">
                    <selectBudgetHotCatalog v-model="item.hotCatalog" keyName="id" keyShow="hotName" placeholder="热点分类" title="热点分类查询" />
                  </el-form-item>
                </div>
                <div class="form-list-content-1">
                  <el-form-item label="备注">
                    <el-input v-model="item.remark" :rows="4" :cols="100" type="textarea" class="textarea-1" placeholder="请输入备注，最多输入3000个字符" />
                  </el-form-item>
                </div>
              </el-card>
            </div>
          </el-col>
        </el-row>
        <el-divider />
        <!-- 项目绩效目标 -->
        <el-row :gutter="24">
          <el-col :sm="24" :lg="24" style="padding-left: 1.25rem">
            <h2>项目绩效目标</h2>
            <el-card class="update-log update-log-1" shadow="hover">
              <div class="tabs-list">
                <h3>绩效目标</h3>
                <el-card class="update-log">
                  <el-form-item label="总体绩效目标" prop="targetAll">
                    <el-input v-model="obj.targetAll" :rows="5" type="textarea" class="textarea-1" placeholder="请输入总体绩效目标" />
                  </el-form-item>
                  <el-form-item label="年度绩效目标" prop="targetCurrent">
                    <el-input v-model="obj.targetCurrent" :rows="5" type="textarea" class="textarea-1" placeholder="请输入年度绩效目标" />
                  </el-form-item>
                </el-card>
                <div class="add-indexs">
                  <h3>本年度绩效指标</h3>
                </div>
                <el-card class="update-log">
                  <el-table :data="kpiListCurrent"
                            style="width: 100%; margin-bottom: 20px"
                            row-key="id"
                            class="indexsTabel"
                            border
                            default-expand-all>
                    <el-table-column prop="kpiName" label="指标名称">
                      <template v-slot="{row}">
                        <span v-if="row && row.level && row.level !== 3">{{ row.kpiName }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="指标名称">
                      <template v-slot="{row}">
                        <el-form-item prop="kpiName" v-if="row && row.level && row.level === 3">
                          <el-autocomplete v-model="row.kpiName"
                                           :fetch-suggestions="querySearch1"
                                           clearable
                                           value-key="name"
                                           placeholder="请输入/选择指标名称"
                                           @select="handleSelectKpi3($event,row)" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="指标解释">
                      <template v-slot="{row}">
                        <el-form-item v-if="row.level === 3" prop="kpiContent">
                          <el-input v-model="row.kpiContent" placeholder="请输入指标解释" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="周期指标值">
                      <template v-slot="{row}">
                        <el-form-item v-if="row.level === 3" prop="kpiValuePeriod">
                          <el-input v-model="row.kpiValuePeriod" placeholder="请输入周期指标值" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="年度指标值">
                      <template v-slot="{row}">
                        <el-form-item v-if="row.level === 3" prop="kpiValue">
                          <el-input v-model="row.kpiValue" placeholder="请输入年度指标值" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="备注">
                      <template v-slot="{row}">
                        <el-form-item v-if="row.level === 3" prop="remark">
                          <el-input v-model="row.remark" placeholder="请输入备注" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="160px" fixed="right">
                      <template #default="scope">
                        <el-button type="primary" link @click="addKpiCurrent(scope.row)" v-if="scope.row.level === 2">
                          新建三级指标
                        </el-button>
                        <el-button type="danger" link @click="deleteKpiCurrent(scope.row)" v-if="scope.row.level === 3">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-divider />
        <!-- 项目预算附件 -->
        <el-row :gutter="24">
          <el-col :sm="24" :lg="24" style="padding-left: 1.25rem">
            <div class="budget-title">
              <h2>项目预算附件</h2>
            </div>
            <div class="file-list-btn">
              <span class="file-list-btn-span">*请按要求上传项目政策依据、资金需求、立项论证情况、其他资料等资料</span>
              <div class="file-list-btns">
                <FileUpload :isShowTip="false" v-model="files" :isShowFileList="false" @uploadedSuccess="uploadedSuccessFn" />
                <!--
                <el-button type="primary" style="margin-left: 20px;">批量下载</el-button>
                -->
              </div>
            </div>
            <el-table :data="files"
                      style="width: 100%; margin-top: 20px"
                      row-key="id"
                      border
                      default-expand-all>
              <el-table-column type="selection" width="55" />
              <el-table-column label="附件类型">
                <template #default="scope">
                  <el-form-item prop="fileType">
                    <el-select v-model="scope.row.fileType" placeholder="请选择附件类型" clearable filterable>
                      <el-option v-for="item in getDictList('BudgetProjectFileType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="original" label="附件名称" />
              <el-table-column align="center" label="操作" width="160px" fixed="right">
                <template #default="scope">
                  <el-button type="primary" link @click="downloadFile(scope.row)">下载</el-button>
                  <el-button type="primary" link @click="viewFile(scope.row)">预览</el-button>
                  <el-button type="danger" link @click="removeFile(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
      <div class="btns" v-if="obj.budgetOneId">
        <el-button @click="handlePreview('obj')" v-if="obj.id">
          <svg-icon icon-class="search" />
          预览
        </el-button>
        <el-button type="success" @click="handleStage('obj')">
          <svg-icon icon-class="save" />
          暂存
        </el-button>
        <el-button type="primary" @click="handleSave('obj')">
          <svg-icon icon-class="save" />
          保存
        </el-button>
        <el-button v-show="checkAuthByCode('')" type="primary" @click="handleSubmit('obj')" v-if="obj.id">
          <svg-icon icon-class="submit" />
          提交审批
        </el-button>
      </div>
    </el-form>
    <el-dialog v-model="dialogViewVisible1" title="预览" width="70%" top="2vh">
      <budgetTwoPreview v-model:budgetTwoId="obj.id" @close="dialogViewVisible1 = false"></budgetTwoPreview>
    </el-dialog>
    <selectApprove v-model:itemsVisible="dialogApproveVisible" @close="dialogApproveVisible = false" :business="'1003'" :businessId="obj.id" @doSubmit="doSubmit" />
    <el-dialog v-model="dialogVisible" title="附件预览" width="70%" top="2vh">
      <attachmentPreview v-model:attachmentId="previewAttachmentId" />
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <selectBudgetOneList v-model:itemsVisible="itemsVisible"
                         v-model:ysySync="itemsVisibleYsySync"
                         v-model:state="itemsVisibleState"
                         @close="itemsVisible = false"
                         @budgetOneSelect="changeBudgetOne" />
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doGetDownload, doPost} from '@/config/http'
import {customValidator, arrChangeTreeFn, alertErrorMsg, notifySuccess, objKeyBuild, getListPageSize, svc} from '@/config/common'
import budgetTwoPreview from '@/views/components/budget/budgetTwoPreview.vue'
import selectBudgetOneList from '@/views/components/budget/selectBudgetOneList.vue'
import attachmentPreview from '@/views/components/base/attachmentPreview.vue'
import selectBudgetCompetent from "@/views/components/budget/selectBudgetCompetent.vue";
import selectApprove from "@/views/components/base/selectApprove.vue";
import User from "@/views/components/base/selectUser.vue";
import selectBudgetHotCatalog from "@/views/components/budget/selectBudgetHotCatalog.vue";
import selectBudgetItemRange from "@/views/components/budget/selectBudgetItemRange.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  budgetOneId: null, // 一上编制ID
  name: null, // 项目名称
  viability: null, // 存续状态
  source: null, // 项目来源
  attribute: null, // 项目属性(新增项目、持续项目、跨年度项目)
  totalFund: 0, // 申请财政总额
  putinFund: 0, // 社会投入资金
  currFund: 0, // 当年资金
  useGovId: null, //用款单位ID
  applyGovId: null, //申报单位ID
  previousArrange: null, //上一年项目预算安排情况
  managerOrgId: null, // 主管部门ID
  managerName: null, // 主管部门联系人
  managerUserContact: null, // 主管部门联系电话
  workGovId: null, // 项目实施单位ID
  workUserId: null, // 项目负责人ID
  workUserContact: null, // 项目负责人联系方式
  state: null, // 状态(0保存、1提交审批、2审批通过、3审批驳回、4撤回)
  startTime: '', // 起始年度
  endTime: '', // 终止年度
  summarize: '',//项目概述
  reason: '', //设立依据及申报理由
  isDebenture: '',//是否债券可用项目
  isScientific: '', // 是否科研项目
  isConstruction: '', // 是否基建项目
  constructionDesc: '', // 基建立项情况
  isAgent: '', // 是否代建项目
  agentGovId: null, //代建单位ID
  isGovernmentPurchase: false, // 是否政府采购
  purchaseProject: null, // 采购项目
  purchaseKind: null, // 采购品目
  purchaseRequire: null, // 采购需求概况
  purchaseDate: null, // 预计采购时间
  fundType: null, // 资金性质
  purchaseAttr: null, // 资金性质
  purchaseFund: 0, // 采购金额
  purchasePrice: 0, // 单价
  purchaseNum: 0, // 采购数量
  purchaseUnit: null, // 计量单位
  targetAll: null, // 项目绩效总目标
  targetCurrent: null, // 项目绩效本年度目标
  applyOneFund: 0, //一上申报金额
  approveOneFund: 0, //一下控制金额
  approveTwoFund: 0, //二下批复金额
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
  approveId: null,
  purchases: [],
  items: [],
  years: [],
  kpis: [],
}

const emptyItem = {
  year: '',
  itemType: null,
  itemRange: null,
  itemName: '',
  itemEconomyType: '',
  itemFunctionType: '',
  unit: '',
  price: 0,
  num: 0,
  according: '',
  remark: '',
}

const emptyPurchase = {
  purchaseItem: '', // 采购项目
  purchaseKind: '', // 采购名目
  purchaseRequire: '', // 采购需求概况
  purchaseDate: '', // 预计采购时间
  purchaseAttr: '', // 资金性质
  purchaseFund: 0, // 采购金额
  purchasePrice: 0, // 单价
  purchaseNum: 0, // 采购数量
  purchaseUnit: '', // purchaseUnit
  fundName: '',
  fundSource: '',
}

const emptyYear = {
  year: '',
  applyFund: 0,
  approveFund: 0,
  budgetFund: 0,
  bringFund: 0,
  thirdCatalog: '',
  hotCatalog: '',
  according: '',
  remark: '',
}

const emptyKpi = {
  id: '',
  budgetOneId: null,
  performanceType: '',
  level: 3,
  kpiCode: '',
  kpiName: '',
  kpiContent: '',
  kpiValue: '',
  remark: '',
  weight: null,
  parentId: null,
  kpiValuePeriod: ''
}

export default {
  name: 'budgetTwoEditForm_nocache',
  mixins: [baseConfig],
  components: {
    selectBudgetItemRange,
    selectBudgetHotCatalog,
    User,
    selectApprove,
    selectBudgetCompetent,
    budgetTwoPreview,
    selectBudgetOneList,
    attachmentPreview
  },
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      kpi2List1: ['数量'],
      kpi2List2: ['经济效益'],
      kpi2List3: ['具体指标'],
      kpi2List4: ['数量'],
      kpi2List5: ['经济效益'],
      kpi2List6: ['具体指标'],
      kpi2Options1: ['数量', '质量', '时效', '成本方面'],
      kpi2Options2: ['经济效益', '时效', '社会效益', '环境效益', '可持续影响等方面'],
      kpi2Options3: ['具体指标'],
      oHeight: 220,
      purchases: [Object.assign({}, emptyPurchase)],
      items: [Object.assign({}, emptyItem)],
      years: [Object.assign({}, emptyYear)],
      kpis: [],
      files: [],
      kpiListAll: [],
      kpiListCurrent: [],
      dialogVisible: false,
      isDisabledEndTime: false,
      endTime: '',
      routes: [],
      oper: null,
      id: null,
      dialogViewVisible: false,
      dialogApproveVisible: false,
      dialogViewVisible1: false,
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      itemsVisible: false,
      itemsVisibleYsySync: null,
      itemsVisibleState: '5',
      previewAttachmentId: '',
      list: null,
      total: 0,
      listLoading: false,
      rules: {
        budgetOneId: [{required: true, validator: customValidator, min: 0, max: 20, label: '一上编制ID', trigger: ['blur', 'change']}],
        code: [{required: false, validator: customValidator, min: 0, max: 50, label: '项目编码', trigger: ['blur', 'change']}],
        name: [{required: true, validator: customValidator, min: 0, max: 100, label: '项目名称', trigger: ['blur', 'change']}],
        viability: [{required: true, validator: customValidator, min: 0, max: 20, label: '存续状态', trigger: ['blur', 'change']}],
        source: [{required: true, validator: customValidator, min: 0, max: 20, label: '项目来源', trigger: ['blur', 'change']}],
        attribute: [{required: true, validator: customValidator, min: 0, max: 20, label: '项目属性', trigger: ['blur', 'change']}],
        totalFund: [{required: true, validator: customValidator, min: 0, max: 13, label: '申请财政总额', trigger: ['blur', 'change']}],
        putinFund: [{required: true, validator: customValidator, min: 0, max: 13, label: '社会投入资金', trigger: ['blur', 'change']}],
        currFund: [{required: true, validator: customValidator, min: 0, max: 13, label: '当年资金', trigger: ['blur', 'change']}],
        useGovId: [{required: true, validator: customValidator, min: 0, max: 20, label: '用款单位ID', trigger: ['blur', 'change']}],
        applyGovId: [{required: true, validator: customValidator, min: 0, max: 20, label: '申报单位ID', trigger: ['blur', 'change']}],
        previousArrange: [{required: true, validator: customValidator, min: 0, max: 200, label: '上一年项目预算安排情况', trigger: ['blur', 'change']}],
        managerOrgId: [{required: true, validator: customValidator, min: 0, max: 20, label: '主管部门', trigger: ['blur', 'change']}],
        managerName: [{required: false, validator: customValidator, min: 0, max: 20, label: '主管部门联系人', trigger: ['blur', 'change']}],
        managerUserContact: [{required: false, validator: customValidator, min: 0, max: 20, label: '主管部门联系电话', trigger: ['blur', 'change']}],
        workGovId: [{required: true, validator: customValidator, min: 0, max: 20, label: '项目实施单位ID', trigger: ['blur', 'change']}],
        workUserId: [{required: true, validator: customValidator, min: 0, max: 20, label: '项目负责人ID', trigger: ['blur', 'change']}],
        workUserContact: [{required: true, validator: customValidator, min: 0, max: 20, label: '项目负责人联系方式', trigger: ['blur', 'change']}],
        state: [{required: true, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change']}],
        startTime: [{required: true, validator: customValidator, min: 0, max: 4, label: '起始年度', trigger: ['blur', 'change']}],
        endTime: [{required: true, validator: customValidator, min: 0, max: 4, label: '终止年度', trigger: ['blur', 'change']}],
        summarize: [{required: true, validator: customValidator, min: 30, max: 3000, label: '项目概述', trigger: ['blur', 'change']}],
        reason: [{required: true, validator: customValidator, min: 30, max: 3000, label: '设立依据及申报理由', trigger: ['blur', 'change']}],
        isDebenture: [{required: true, validator: customValidator, min: 0, max: 20, label: '是否债券可用项目', trigger: ['blur', 'change']}],
        isScientific: [{required: true, validator: customValidator, min: 0, max: 20, label: '是否科研项目', trigger: ['blur', 'change']}],
        isConstruction: [{required: true, validator: customValidator, min: 0, max: 20, label: '是否基建项目', trigger: ['blur', 'change']}],
        constructionDesc: [{required: true, validator: customValidator, min: 0, max: 20, label: '基建立项情况', trigger: ['blur', 'change']}],
        isAgent: [{required: true, validator: customValidator, min: 0, max: 20, label: '是否代建项目', trigger: ['blur', 'change']}],
        agentGovId: [{required: false, validator: customValidator, min: 0, max: 20, label: '代建单位ID', trigger: ['blur', 'change']}],
        isGovernmentPurchase: [{required: false, validator: customValidator, min: 0, max: 20, label: '是否政府采购', trigger: ['blur', 'change']}],
        purchaseProject: [{required: false, validator: customValidator, min: 0, max: 100, label: '采购项目', trigger: ['blur', 'change']}],
        purchaseKind: [{required: false, validator: customValidator, min: 0, max: 100, label: '采购品目', trigger: ['blur', 'change']}],
        purchaseRequire: [{required: false, validator: customValidator, min: 0, max: 200, label: '采购需求概况', trigger: ['blur', 'change']}],
        purchaseDate: [{required: false, validator: customValidator, min: 0, max: 0, label: '预计采购时间', trigger: ['blur', 'change']}],
        purchaseAttr: [{required: false, validator: customValidator, min: 0, max: 200, label: '资金性质', trigger: ['blur', 'change']}],
        purchaseFund: [{required: false, validator: customValidator, min: 0, max: 13, label: '采购金额', trigger: ['blur', 'change']}],
        purchasePrice: [{required: false, validator: customValidator, min: 0, max: 13, label: '单价', trigger: ['blur', 'change']}],
        purchaseNum: [{required: false, validator: customValidator, min: 0, max: 5, label: '采购数量', trigger: ['blur', 'change']}],
        purchaseUnit: [{required: false, validator: customValidator, min: 0, max: 20, label: '计量单位', trigger: ['blur', 'change']}],
        fundName: [{required: false, validator: customValidator, min: 0, max: 200, label: '专项资金名称', trigger: ['blur', 'change']}],
        fundSource: [{required: false, validator: customValidator, min: 0, max: 200, label: '资金来源', trigger: ['blur', 'change']}],
        targetAll: [{required: true, validator: customValidator, min: 0, max: 0, label: '项目绩效总目标', trigger: ['blur', 'change']}],
        targetCurrent: [{required: true, validator: customValidator, min: 0, max: 0, label: '项目绩效本年度目标', trigger: ['blur', 'change']}],
      },
      catalogProjectList: [],
      approveList: [], //审批模版list
      thirdCatalogList: initListStore().thirdCatalogList,
      hotCatalogList: initListStore().hotCatalogList,
      governmentList: initListStore().governmentList,
      organizationList: initListStore().organizationList,
      userList: initListStore().userList,
      itemTypeList: initListStore().itemTypeList,
      itemRangeList: initListStore().itemRangeList,
      itemRangeAllList: initListStore().itemRangeAllList,
      inc: 1000,
      kpi3List: initListStore().kpi3List
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.initObj()
    // this.initList()
    this.initCatalogProjectTwoList()
  },
  methods: {
    arrChangeTreeFn,
    async initCatalogProjectTwoList() {
      this.catalogProjectList = []
      let p1 = doGet(this.svc, '/budget-catalog/page', {state: '1', pageSize: getListPageSize()}, false)
      let p2 = doGet(this.svc, '/budget-project-one/page', {pageSize: getListPageSize()}, false)
      let p3 = doGet(this.svc, '/budget-project-two/page', {pageSize: getListPageSize()}, false)
      let resArray = await Promise.all([p1, p2, p3])
      let clist = resArray[0]['records']
      let p1list = resArray[1]['records']
      let p2list = resArray[1]['records']
      let slist = resArray[2]['records']
      clist.forEach((curr) => {
        let cu = {}
        cu.value = curr.catalogCode
        cu.label = curr.catalogCode + ' - ' + curr.catalogName
        cu.children = []
        p1list.forEach((child1) => {
          if (child1.catalogId === curr.id && child1.parentId === null) {
            child1.value = child1.id
            child1.label = child1.code + ' - ' + child1.name
            child1.children = []
            p2list.forEach((child2) => {
              if (child2.parentId === child1.id) {
                child2.value = child2.id
                child2.label = child2.code + ' - ' + child2.name
                child2.children = []
                slist.forEach((sub) => {
                  if (sub.budgetOneId === child2.id) {
                    sub.value = sub.id
                    sub.label = sub.code + ' - ' + sub.name
                    sub.children = []
                    // console.debug("sub",sub)
                    child2.children.push(sub)
                  }
                })
                child1.children.push(child2)
              }
            })
            cu.children.push(child1)
          }
        })
        this.catalogProjectList.push(cu)
      })
    },
    // async initList() {
    //   let p1 = doGet(this.svc, '/budget-third-catalog/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/budget-hot-catalog/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/government/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p5 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p6 = doGet(this.svc, '/budget-item-type/page', {pageSize: getListPageSize()}, false)
    //   let p7 = doGet(this.svc, '/budget-item-range/page', {pageSize: getListPageSize()}, false)
    //   let p8 = doGet(this.svc, '/budget-kpi/page', {pageSize: getListPageSize(), sortField: 'weight', sortType: 'asc'}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8])
    //   this.thirdCatalogList = resArray[0]['records']
    //   this.hotCatalogList = resArray[1]['records']
    //   this.governmentList = resArray[2]['records']
    //   this.organizationList = resArray[3]['records']
    //   this.userList = resArray[4]['records']
    //   this.itemTypeList = arrChangeTreeFn(resArray[5]['records']).reverse();
    //   this.itemRangeAllList = resArray[6]['records'].reverse();
    //   this.kpi3List = resArray[7]['records'].filter(item => item.level === 3)
    // },
    async initObj() {
      this.oper = this.$route.query.oper
      this.id = null
      if (this.$route.query.id) {
        // 编辑
        this.id = this.$route.query.id
        this.obj = await doGet(this.svc, `/budget-two/${this.id}`, {}, true)
        if (this.obj.viability === '1') {
          this.obj.endTime = '2099'
          this.isDisabledEndTime = true
        } else {
          this.endTime = this.obj.endTime
        }
        let p1 = doGet(this.svc, '/budget-two-purchase/listByField', {field: 'budgetTwoId', values: this.id}, false)
        let p2 = doGet(this.svc, '/budget-two-item/listByField', {field: 'budgetTwoId', values: this.id}, false)
        let p3 = doGet(this.svc, '/budget-two-year/listByField', {field: 'budgetTwoId', values: this.id}, false)
        let p4 = doGet(this.svc, '/budget-two-kpi/listByField', {field: 'budgetTwoId', values: this.id, sortField: 'weight', sortType: 'asc'}, false)
        let p5 = doGet(this.svc, '/budget-two-file/listByField', {field: 'budgetTwoId', values: this.id}, false)
        let resArray = await Promise.all([p1, p2, p3, p4, p5])
        this.purchases = resArray[0]
        this.items = resArray[1]
        // 开支范围回显
        this.obj.totalFund = 0
        this.items.forEach((item, index) => {
          this.obj.totalFund += item.price * item.num
          if (item.itemType) {
            this.categoryChange(item.itemType, item, index)
          } else {
            this.itemRangeList[index] = this.itemRangeAllList
          }
        })
        this.years = resArray[2]
        this.kpis = resArray[3]
        let kpiListCurrent = this.kpis.filter(item => item.performanceType === '1')
        this.kpiListCurrent = arrChangeTreeFn(kpiListCurrent)
        this.files = resArray[4]
        this.files = this.files.map(item => {
          item.original = item.attachmentName
          return item
        })
      }
    },
    buildYearsRefreshTotalFund() {
      this.years = []
      this.obj.totalFund = 0
      for (let idx in this.items) {
        let item = this.items[idx]
        if (!item.year)
          continue
        let ye = Object.assign({}, emptyYear)
        ye.year = item.year
        ye.applyFund = item.price * item.num
        this.obj.totalFund += item.price * item.num
        let found = false
        for (let k in this.years) {
          if (this.years[k].year === ye.year) {
            this.years[k].applyFund += item.price * item.num
            found = true
          }
        }
        if (!found)
          this.years.push(ye)
      }
    },
    uploadedSuccessFn(file) {
      this.files.push(file)
    },
    buildObj() {
      let o = this.obj
      //purchases
      o.purchases = []
      for (let idx in this.purchases) {
        o.purchases.push(this.purchases[idx])
      }
      //items
      o.items = []
      o.items = this.items.map(item => {
        console.debug('typeof(item.itemType)', typeof (item.itemType))
        if (item.itemType && typeof (item.itemType) === 'object' && item.itemType.length > 0) {
          console.debug('item.itemType', item.itemType)
          item.itemType = item.itemType[1]
        }
        return item
      })

      o.useGovId = objKeyBuild(o.useGovId)
      o.applyGovId = objKeyBuild(o.applyGovId)
      o.workGovId = objKeyBuild(o.workGovId)
      o.agentGovId = objKeyBuild(o.agentGovId)

      //years
      o.years = []
      for (let idx in this.years) {
        o.years.push(this.years[idx])
      }
      //kpis
      o.kpis = []
      for (let i in this.kpiListAll) {
        let one = this.kpiListAll[i]
        o.kpis.push(one)
        for (let j in one.children) {
          let two = one.children[j]
          o.kpis.push(two)
          for (let k in two.children) {
            let three = two.children[k]
            o.kpis.push(three)
          }
        }
      }
      for (let i in this.kpiListCurrent) {
        let one = this.kpiListCurrent[i]
        o.kpis.push(one)
        for (let j in one.children) {
          let two = one.children[j]
          o.kpis.push(two)
          for (let k in two.children) {
            two.children[k].weight = k + 1
            let three = two.children[k]
            o.kpis.push(three)
          }
        }
      }
      //files
      o.files = this.files.map(item => {
        return {
          attachmentId: item.id,
          attachmentName: item.original,
          fileType: item.fileType
        }
      })
      // console.debug('o.files----',o.files)
      return o
    },
    openProjectModel() {
      this.itemsVisible = true
    },
    async changeBudgetOne(data) {
      let o = await doGet(this.svc, '/budget-two/listByField', {field: 'budgetOneId', values: data.id}, true)
      if (o && o.length > 0) {
        console.debug("找到二上编制，作为修改")
        this.obj = o[0];
        this.obj.previousArrange = parseFloat(data.previousArrange.toString())
        if (this.obj.viability === '1') {
          this.obj.endTime = '2099'
          this.isDisabledEndTime = true
        } else {
          this.endTime = this.obj.endTime
        }
        let p1 = doGet(this.svc, '/budget-two-purchase/listByField', {field: 'budgetTwoId', values: this.obj.id}, false)
        let p2 = doGet(this.svc, '/budget-two-item/listByField', {field: 'budgetTwoId', values: this.obj.id}, false)
        let p3 = doGet(this.svc, '/budget-two-year/listByField', {field: 'budgetTwoId', values: this.obj.id}, false)
        let p4 = doGet(this.svc, '/budget-two-kpi/listByField', {field: 'budgetTwoId', values: this.obj.id, sortField: 'weight', sortType: 'asc'}, false)
        let p5 = doGet(this.svc, '/budget-two-file/listByField', {field: 'budgetTwoId', values: this.obj.id}, false)
        let resArray = await Promise.all([p1, p2, p3, p4, p5])
        this.purchases = resArray[0]
        this.items = resArray[1]
        this.years = resArray[2]
        this.kpis = resArray[3]
        let kpiListCurrent = this.kpis.filter(item => item.performanceType === '1')
        this.kpiListCurrent = arrChangeTreeFn(kpiListCurrent)
        this.files = resArray[4]
        this.files = this.files.map(item => {
          item.original = item.attachmentName
          return item
        })
      } else {
        console.debug("没有找到二上编制，作为新增")
        this.obj = data
        this.obj.previousArrange = parseFloat(data.previousArrange.toString())
        this.obj.budgetOneId = data.id
        if (this.obj.viability === '1') {
          this.obj.endTime = '2099'
          this.isDisabledEndTime = true
        } else {
          this.endTime = this.obj.endTime
        }
        let p1 = doGet(this.svc, '/budget-one-purchase/listByField', {field: 'budgetOneId', values: data.id}, false)
        let p2 = doGet(this.svc, '/budget-one-item/listByField', {field: 'budgetOneId', values: data.id}, false)
        let p3 = doGet(this.svc, '/budget-one-year/listByField', {field: 'budgetOneId', values: data.id}, false)
        let p4 = doGet(this.svc, '/budget-one-kpi/listByField', {field: 'budgetOneId', values: data.id, sortField: 'weight', sortType: 'asc'}, false)
        let p5 = doGet(this.svc, '/budget-one-file/listByField', {field: 'budgetOneId', values: data.id}, false)
        let resArray = await Promise.all([p1, p2, p3, p4, p5])
        this.purchases = resArray[0]
        this.items = resArray[1]
        this.years = resArray[2]
        this.kpis = resArray[3]
        let kpiListCurrent = this.kpis.filter(item => item.performanceType === '1')
        this.kpiListCurrent = arrChangeTreeFn(kpiListCurrent)
        this.files = resArray[4]
        console.debug('this.files', this.files)
        this.files = this.files.map(item => {
          item.original = item.attachmentName
          return item
        })
        this.obj.id = null
        this.obj.code = null
        this.obj.state = null
      }
    },
    async doStage() {
      let o = this.buildObj()
      let res = await doPost(this.svc, '/customBudgetTwo/stageBudgetTwo', o, true);
      this.obj.id = res['id']
      this.obj.code = res['code']
      this.obj.version = res['version']
    },
    async handlePreview(formName) {
      console.debug(formName)
      await this.doStage()
      this.dialogViewVisible1 = true
    },
    async handleStage(formName) {
      console.debug(formName)
      await this.doStage()
      notifySuccess('暂存成功')
      this.dialogViewVisible = false
    },
    async handleSave(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.buildObj()
      await doPost(this.svc, '/customBudgetTwo/saveBudgetTwo', o, true);
      notifySuccess('保存成功')
      this.goTargetByName('budgetTwo', {}, true)
      this.dialogViewVisible = false
    },
    async handleSubmit(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      await this.doStage()
      this.dialogApproveVisible = true
    },
    async doSubmit(data) {
      let o = this.buildObj()
      o.approveId = data.approveId
      o.approveNodes = data.approveNodes
      await doPost(this.svc, '/customBudgetTwo/submitBudgetTwo', o, false);
      notifySuccess('提交成功')
      this.goTargetByName('budgetTwo', {}, true)
      this.dialogViewVisible = false
    },
    MathRand() {
      let Num = "";
      for (let i = 0; i < 5; i++) {
        Num += Math.floor(Math.random() * 10);
      }
      return Num
    },
    addKpiAll(row) {
      let obj = Object.assign({}, emptyKpi)
      obj.parentId = row.id
      obj.id = this.inc++
      obj.performanceType = '0'
      if (row.children) {
        row.children.push(obj)
      } else {
        row.children = [obj]
      }
    },
    deleteKpiAll(row) {
      this.kpiListAll.forEach((one) => {
        if (one.performanceType === '0') {
          one.children.forEach((two) => {
            if (two.performanceType === '0' && two.level === '2' && two.id === row.parentId) {
              let index = two.children.findIndex(item1 => item1.id === row.id)
              two.children.splice(index, 1)
            }
          })
        }
      })
    },
    querySearch1(queryString, cb) {
      const results = queryString
          ? this.kpi3List.filter(item => item.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
          : this.kpi3List
      console.debug('results==========', results)
      // call callback function to return suggestions
      cb(results)
    },
    handleSelectKpi3(val, row) {
    },
    addKpiCurrent(row) {
      let obj = Object.assign({}, emptyKpi)
      obj.parentId = row.id
      obj.id = this.inc++
      obj.performanceType = '1'
      obj.level = 3
      if (row.children) {
        row.children.push(obj)
      } else {
        row.children = [obj]
      }
    },
    deleteKpiCurrent(row) {
      this.kpiListCurrent.forEach((one) => {
        if (one.performanceType === '1') {
          one.children.forEach((two) => {
            if (two.performanceType === '1' && two.level === 2 && two.id === row.parentId) {
              let index = two.children.findIndex(item1 => item1.id === row.id)
              two.children.splice(index, 1)
            }
          })
        }
      })
    },
    getTreeTableParentRow(baseRow, row) {
      let prow = null;
      let children = baseRow.children;
      if (children && children.length > 0) {
        children.forEach((item) => {
          if (row.parentId === item.id) {
            prow = item;
          } else {
            prow = this.getTreeTableParentRow(item, row);
          }
        });
      }
      if (prow) {
        return prow
      }
    },
    // 树结构组装
    // 新增政府预算
    addGovernmentBudget() {
      let item = Object.assign({}, emptyPurchase)
      this.purchases.push(item)
    },
    removeGovernmentBudget(index) {
      this.purchases.splice(index, 1)
    },
    // 新增预算明细
    addItem() {
      let item = Object.assign({}, emptyItem)
      this.items.push(item)
      this.buildYearsRefreshTotalFund()
    },
    // 删除预算明细
    removeItem(index) {
      this.items.splice(index, 1)
      this.buildYearsRefreshTotalFund()
    },
    viabilityChange(val) {
      console.debug('val-----', val)
      if (val === '1') {
        this.obj.endTime = '2099'
        this.isDisabledEndTime = true
      } else {
        this.isDisabledEndTime = false
        this.obj.endTime = this.endTime
      }
    },
    startTimeChange(val) {
      console.debug(val)
      // this.endTime = val
      this.items = []
      if (this.obj.viability === '1') {
        let item = Object.assign({}, emptyItem)
        item.year = String(this.obj.startTime)
        item.itemName = null
        item.unit = null
        item.price = 0
        item.num = 0
        item.according = ''
        item.remark = ''
        this.items.push(item)
        this.buildYearsRefreshTotalFund()
      } else {
        if (this.obj.endTime && parseInt(this.obj.endTime) > parseInt(this.obj.startTime)) {
          let yearsNum = parseInt(this.obj.endTime) - parseInt(this.obj.startTime)
          for (let i = 0; i < yearsNum + 1; i++) {
            let item = Object.assign({}, emptyItem)
            item.year = String(parseInt(this.obj.startTime) + i)
            item.itemName = ''
            item.unit = ''
            item.price = 0
            item.num = 0
            item.according = ''
            item.remark = ''
            this.items.push(item)
          }
          console.debug('this.items----', this.items)
          this.buildYearsRefreshTotalFund()
        }
      }
    },
    endTimeChange(val) {
      this.endTime = val
      this.items = []
      if (this.obj.startTime && parseInt(this.obj.endTime) > parseInt(this.obj.startTime) && this.obj.viability === '2') {
        let yearsNum = parseInt(this.obj.endTime) - parseInt(this.obj.startTime)
        for (let i = 0; i < yearsNum + 1; i++) {
          let item = Object.assign({}, emptyItem)
          item.year = String(parseInt(this.obj.startTime) + i)
          item.itemName = ''
          item.unit = ''
          item.price = 0
          item.num = 0
          item.according = ''
          item.remark = ''
          this.items.push(item)
        }
        console.debug('this.items----', this.items)
        this.buildYearsRefreshTotalFund()
      } else {
        if (this.obj.startTime) {
          let item = Object.assign({}, emptyItem)
          item.year = String(this.obj.startTime)
          item.itemName = ''
          item.unit = ''
          item.price = 0
          item.num = 0
          item.according = ''
          item.remark = ''
          this.items.push(item)
          this.buildYearsRefreshTotalFund()
        }
      }
    },
    disabledDate1(data) {
      return parseInt(this.obj.startTime) > data.getFullYear() || parseInt(this.obj.endTime) < data.getFullYear()
    },
    disabledDateStart(data) {
      return data.getFullYear() < new Date().getFullYear()
    },
    disabledDateEnd(data) {
      if (this.obj.startTime) {
        return parseInt(this.obj.startTime) > data.getFullYear()
      } else {
        return data.getFullYear() < new Date().getFullYear()
      }
    },
    // 年度资金计划数据生成
    yeerPlanData() {

    },
    downloadFile(row) {
      doGetDownload(svc, '/customAttachment/download/' + row.attachmentId, {})
    },
    viewFile(row) {
      this.dialogVisible = true
      setTimeout(() => {
        this.previewAttachmentId = row.attachmentId
      }, 500)
    },
    removeFile(scope) {
      this.files.splice(scope.$index, 1)
    },
    categoryChange(val, item, index) {
      let id = typeof (val) === 'object' ? val[1] : val
      item.itemRange = typeof (val) === 'object' ? null : item.itemRange
      doGet(this.svc, '/budget-item-type-range/listByField', {field: 'itemTypeId', values: id}, false).then(res => {
        if (res?.length > 0) {
          let ids = []
          res?.map(item => {
            ids.push(item.itemRangeId)
          })
          doGet(this.svc, '/budget-item-range/ids', {ids: ids.join(',')}, false).then(r => {
            this.itemRangeList[index] = r
          })
        }
      })
    },
    changeManagerOrgId(o) {
      this.obj.managerName = o.contact
      this.obj.managerUserContact = o.telephone
    },
  },
}
</script>
<style scoped>
.form-radio1 {
  margin-top: 1rem;
}
.form-list {
  display: flex;
  flex-wrap: wrap;
  /* align-items: center; */
  /* justify-content: space-between; */
}
.form-list-content {
  display: flex;
  flex-wrap: wrap;
}
.form-label {
  display: inline-flex;
  justify-content: flex-end;
  align-items: flex-start;
  flex: 0 0 auto;
  /* font-size: var(--el-form-label-font-size); */
  font-size: 1rem;
  /* color: var(--el-text-color-regular); */
  color: #337ecc;
  height: 2rem;
  line-height: 2rem;
  padding: 0 .75rem 0 0;
  box-sizing: border-box;
  width: 8rem;
  font-weight: bold;
}
.form-label-2 {
  width: 11.25rem;
}
.form-label-1 {
  width: 18.75rem;
  justify-content: flex-start;
  margin-left: 1.375rem;
  color: #c45656;
}
.form-label-1 span {
  font-size: 1.25rem;
}
.budget-title {
  display: flex;
  align-items: center;
}
.budget-title-left {
  display: flex;
  align-items: center;
}
.budget-title-1 {
  justify-content: space-between;
}
.budget-title h2 {
  margin-right: 1.25rem;
}
.ico-list {
  margin-left: .625rem;
}
.btns {
  margin: 1.875rem 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.update-log {
  margin-bottom: 20px;
}
.update-log-1 {
  margin-top: 20px;
}
.add-indexs {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.file-list-btn {
  display: flex;
  /* display: flex; */
  align-items: center;
  justify-content: space-between
}
.file-list-btns {
  display: flex;
  align-items: center;
}
.file-list-btn-span {
  color: #F56C6C;
  font-size: 12px;
}
.totalFund {
  min-width: 500px;
  position: fixed;
  border: 1px solid #ccc;
  top: 140px;
  right: 0;
  z-index: 100;
  /* display: inline-block; */
  /* border: 1px solid #c45656; */
  background: #fff;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  justify-content: end;
  /* border-radius: 10px; */
}
</style>
